package com.example.database;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.wificovv2.SeekAp;
import com.example.wificov.SamplingPowPic;
import com.example.wificovv2.WSTActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class MyWifi extends BroadcastReceiver{
	private WSTActivity wst;
	private SamplingPowPic sample;
	WifiManager wifi;
	BroadcastReceiver receiver;
	List<ScanResult> results;
	public MyWifi(WSTActivity wstActivity) {
		super();
		wst = wstActivity;
	}
	public MyWifi(SamplingPowPic sampling) {
		super();
		sample = sampling;
	}
	public String Init()
	{
		String textStatus = "";
		// Setup WiFi
		wifi = (WifiManager) wst.getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            wifi.setWifiEnabled(true);
        } 
		// Register Broadcast Receiver
		wst.registerReceiver(this, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		// Get WiFi status
		WifiInfo info = wifi.getConnectionInfo();
		textStatus += "\n\nWiFi Status: " + info.toString();
		// List available networks
		List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
		//String channel = new String();
		for (WifiConfiguration config : configs) {
			textStatus += "\n\n" + config.toString();
			// Direct use of Pattern:
			 Pattern p1 = Pattern.compile("Channel:\\s+(\\d+)");
			 Matcher m1 = p1.matcher(config.toString());
			 //String frequency= new String();
			 if (m1.find()) { // Find each match in turn; String can't do this.
				 textStatus += "\n\n" + m1.group(1); // Access a submatch group; String can't do this.
			 }
			 
		}
		return textStatus;
	}
	
	public void End()
	{
		wst.unregisterReceiver(this);
	}
	
	public void StartScan()
	{
		
		wifi.startScan();		
	}
	
	/* (non-Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
	    List<ScanResult> results = this.wifi.getScanResults();
	    wst.UpdateListWifi(results);
	    //sample.UpdateWifiInfo();
	}
	

}
